package com.example.dma.service;

import com.example.dma.pojo.User;
import com.example.dma.repository.UserRepository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private UserRepository userRepository;

    public User addUser(User user) {
        return userRepository.save(user); // 保存用户到数据库
    }

    public User updateUser(User user) {
        return userRepository.save(user);
    }

    public User deleteUser(User user) {
        userRepository.delete(user);
        return user;
    }

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
    public boolean userExists(String username) {
        User user = userRepository.findByUsername(username);
        return user != null;
    }
    public boolean validateUserCredentials(String username, String password) {
        User user = userRepository.findByUsername(username); // 查找用户
        if (user != null) {
            return user.getPassword().equals(password); // 验证密码是否匹配
        }
        return false; // 用户未找到
    }
    public String getEmailByUname(String name) {
        List<User> users = userRepository.findAll();
        for (User user : users) {
            if (user.getUsername().equals(name)) {
                return user.getEmail();
            }
        }
        return null;
    }

    public User getUserByUsername(String name) {
        List<User> users = userRepository.findAll();
        for (User user : users) {
            if (user.getUsername().equals(name)) {
                return user;
            }
        }
        return null;
    }
}
